<template>
  <div class="mycourse-wrapper">
    <div class="courses-content">
      <CourseItem v-for="course in courses" :key="course.id" :course="course"></CourseItem>
    </div>
    <template v-if="isTeacher">
      <hr>
      <button class="create-btn" @click="showCreateDialog=true">
          <i class="el-icon-plus"></i>
          创建课程
      </button>
      <div class="dialog" v-if="isTeacher && showCreateDialog">
          <div class="dialog-title">
              创建课程
              <button class="dialog-close" @click="showCreateDialog=false"><i class="el-icon-close"></i></button>
          </div>
          <el-form class="form" label-width="80px">
              <el-form-item label="课程名">
                  <el-input size="small" type="text" v-model="courseForm.name" required></el-input>
              </el-form-item>
              <el-form-item label="语言">
                  <el-select size="small" @change="change" v-model="courseForm.language" name="language" required>
                      <el-option value="C" label="C"></el-option>
                      <el-option value="C++" label="C++"></el-option>
                      <el-option value="Java" label="Java"></el-option>
                      <el-option value="Fortran" label="Fortran"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="班级人数">
                <el-input-number
                  v-model="courseForm.count"
                  :min="1"></el-input-number>
              </el-form-item>
              <el-form-item label="有效期限">
                  <el-date-picker
                    class="date-picker"
                    size="small"
                    v-model="courseForm.date"
                    type="daterange"
                    value-format="timestamp"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
              </el-form-item>
              <el-form-item label="课程图片">
                  <img :src="courseForm.img" alt="" class="course-img">
                  <div class="pick-file-btn" @click="selectImg">
                      本地
                      <img src="../assets/本地.png" alt="" class="pick-file-btn-icon">
                  </div>
                  <input type="file" accept="image/*" ref="img-picker" @change="showImg" style="display:none">
              </el-form-item>
              <el-form-item>
                  <el-button class="submit-btn" @click="createCourse">创建</el-button>
              </el-form-item>
          </el-form>
      </div>
    </template>
  </div>
</template>
<script>
import CourseItem from './CourseItem'
import { getMyCourse, createCourse } from '@/utils/api'

export default {
  name: 'mycourse',
  components: {
    CourseItem
  },
  data () {
    return {
      covers: {
        'C': 'http://shancloud.cn/media/default/C.png',
        'C++': 'http://shancloud.cn/media/default/C++.png',
        'Java': 'http://shancloud.cn/media/default/Java.png',
        'Fortran': 'http://shancloud.cn/media/default/Fortran.png'
      },
      showCreateDialog: false,
      // courses: [{
      //   id: 1,
      //   name: '课程名称',
      //   date: '2018.1.1-2018.1.15',
      //   teacher: '杨杨杨',
      //   language: 'C',
      //   count: 39,
      //   waitHandle: 10
      // }],
      courseForm: {
        name: '',
        language: 'C',
        date: '',
        // img: require('../assets/C语言图片.png'),
        img: 'http://shancloud.cn/media/default/C.png',
        count: 100
      }
    }
  },
  computed: {
    isTeacher () {
      return this.$store.getters.isTeacher
    },
    userId () {
      return this.$store.state.userInfo.id
    },
    courses () {
      return this.$store.state.courses
    }
  },
  methods: {
    checkField () {
      let form = {
        course_name: this.courseForm.name.trim(),
        programming_language: this.courseForm.language.trim(),
        start_time: this.timestampToTime(this.courseForm.date[0]),
        end_time: this.timestampToTime(this.courseForm.date[1]),
        course_image: this.courseForm.img,
        student_num: this.courseForm.count
      }
      for (let key in form) {
        if ((typeof form[key] === 'string' && form[key].length <= 0) || !form[key]) {
          this.$notify({
            title: '请完整填写',
            message: '请完整填写',
            type: 'warning'
          })
          return false
        }
      }
      return form
    },
    timestampToTime (timestamp) {
      console.log(timestamp)
      let date = new Date(timestamp)
      console.log(date.getFullYear())
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = date.getDate()
      return Y + M + D
    },
    async createCourse () {
      let form = this.checkField()
      if (form) {
        form.user_id = this.userId
        let res = await createCourse(form)
        if (res.error === '10') {
          this.$notify({
            title: '操作成功',
            message: '课程创建成功',
            type: 'success'
          })
          this.showCreateDialog = false
          for (let key in this.courseForm) {
            this.courseForm[key] = ''
          }
          this.getMyCourse()
        } else {
          this.$notify({
            title: '操作失败',
            message: `原因: ${res.result}`,
            type: 'error'
          })
        }
      }
    },
    selectImg () {
      this.$refs['img-picker'].click()
    },
    showImg (e) {
      if (e.target.files.length > 0) {
        this.courseForm.img = URL.createObjectURL(e.target.files[0])
      }
    },
    async getMyCourse () {
      let res = await getMyCourse()
      if (res.error === '10') {
        this.$store.commit('setCourses', res.result)
      } else {
        this.$notify({
          title: '获取课程出错',
          message: res.result,
          type: 'error'
        })
      }
    },
    change (item) {
      this.courseForm.img = this.covers[item]
    }
  },
  mounted () {
    // if (!this.courses.length) {
    this.getMyCourse()
    // }
  }
}
</script>

<style lang="less">
.mycourse-wrapper {
  width: 60%;
  margin: 0 auto;
  min-height: calc(~'100vh - 320px');
  @media screen and (max-width: 768px){
    width: 96%;
  }
  &>* {
    margin-left: -30px;
  }
  .create-btn {
    width: 236px;
    height: 160px;
    background: #6fce7c;
    color: #fff;
    border: none;
    margin: 20px 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .create-btn > *:first-child {
    margin-right: 10px;
    font-size: 20px;
  }
  .dialog {
    width: 500px;
    position: fixed;
    top: 100px;
    left: 50%;
    margin-left: -200px;
    background: #fff;
    box-shadow: 0 0 20px #bbb;
    border: 1px solid #bbb;
    @media screen and (max-width: 768px) {
      width: 100%;
      & input {
        max-width: 200px;
      }
      & .el-date-editor{
        width: 250px;
      }
    }
  }
  .dialog-title {
    background: #0195dd;
    padding: 15px 20px;
    color: #fff;
  }
  button.dialog-close {
    border: none;
    outline: none;
    background: transparent;
    color: #fff;
    font-size: 20px;
    float: right;
  }
  .dialog .form {
    width: 400px;
    margin: 40px auto;
    @media screen and (max-width: 768px) {
      width: auto;
      padding: 0 20px;
    }
  }
  .dialog .course-img {
    width: 160px;
    vertical-align: top;
    padding-top: 10px;
  }
  .dialog input {
    border-radius: 0;
  }
  .dialog .pick-file-btn {
    border: none;
    padding-left: 0;
    display: inline-block;
    cursor: pointer;
  }
  .dialog .submit-btn {
    margin-left: 200px;
    border-radius: 0;
    width: 120px;
    @media screen and (max-width: 768px){
      margin-left: 0;
    }
  }
  .dialog .date-picker {
    border-radius: 0;
  }
}
</style>
